<template>
  <div>
    <el-form class="query-table-form" :inline="true">
      <el-form-item>
        <el-input v-model="params.enterprise_name" placeholder="企业名称查询" clearable>
          <i class="el-icon-search el-input__icon" slot="suffix" @click="getData()"></i>
        </el-input>
      </el-form-item>
      <el-form-item>
        <c-select
          :options="enumInvoiceStatus"
          placeholder="发票状态"
          v-model="params['invoice_status.eq']"
          clearable
          @change="getData()"
        ></c-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="getData()">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button
          icon="el-icon-download"
          :loading="exportLoading"
          @click="exportExcel('保函台账')"
        >
          台账下载
        </el-button>
      </el-form-item>
      <div class="text-muted" v-loading="countLoading">
        <div>
          合计： 开标数：
          <span class="text-danger">{{ countData.p }}</span>
          ，企业数：
          <span class="text-danger">{{ countData.p3 }}</span>
        </div>
        项目总数：
        <span class="text-danger">{{ totalCount || '-' }}</span>
        , 担保金额：
        <span class="text-danger">{{ countData.p1 || '-' }}</span>

        元, 担保费：
        <span class="text-danger">{{ countData.p2 || '-' }}</span>
        元 。
      </div>
    </el-form>

    <c-table border v-loading="loading" :columns="tableColumns" :data="tableData"></c-table>
    <div class="query-pagination">
      <div></div>
      <el-pagination
        layout="total, prev, pager, next, jumper"
        :current-page.sync="params.index"
        :page-size="params.size"
        :total="totalCount"
        @current-change="getData"
      ></el-pagination>
    </div>

    <info-view :visible.sync="infoVisible" :query-id="infoId"></info-view>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import InfoView from '@/bigcredit/views/letter/apply/info/IndexDialog'
import { exportExcel } from '@/credit/mixin/taskTableProvinceUnion'
export const enumInvoiceStatus = {
  0: '未申请',
  1: '已申请',
  2: '已开具',
  3: '已作废',
}
export const enumInvoiceStyle = {
  0: 'info',
  1: 'warning',
  2: 'success',
}

export const enumIsExpire = {
  0: '正常',
  1: '到期',
}
export default {
  components: {
    InfoView,
  },
  props: {},
  data() {
    return {
      enumInvoiceStatus,
      params: {
        index: 1,
        size: 10,
        'pay_status.eq': 2,
      },
      order: { create_time: 'desc' },
      loading: false,
      totalCount: 0,
      tableName: 'guarantee_project',
      tableData: [],
      countData: {},
      tableColumns: [
        {
          attrs: { label: '序号', prop: 'index', align: 'center' },
        },
        { attrs: { label: '企业名称', prop: 'enterprise_name', align: 'center' } },
        { attrs: { label: '标段/标包编号', prop: 'section', align: 'center' } },
        { attrs: { label: '营业执照号', prop: 'enterprise_code', align: 'center' } },
        { attrs: { label: '申请日期', prop: 'create_time', width: 100 } },
        { attrs: { label: '联系电话', prop: 'agent_phone', align: 'center' } },
        { attrs: { label: '联系人', prop: 'agent_name', align: 'center' } },
        { attrs: { label: '担保金额（元）', prop: 'tender_bond', align: 'center' } },
        {
          attrs: { label: '担保费率', prop: 'guaRate', align: 'center' },
        },
        { attrs: { label: '担保费（元）', prop: 'gua_fee', align: 'center' } },
        { attrs: { label: '开函时间', prop: 'payTime', align: 'center', width: '100' } },

        { attrs: { label: '保函类型', prop: 'letterType', align: 'center' } },
        { attrs: { label: '保函编号', prop: 'guarantee_no', align: 'center' } },

        { attrs: { label: '开标时间', prop: 'openTime', width: 100 } },
        { attrs: { label: '保函状态', prop: 'letterStatus', align: 'center' } },
        { attrs: { label: '发票状态', prop: 'invoiceStatus', align: 'center' } },
        {
          attrs: { label: '操作', align: 'center', width: 100, fixed: 'right' },
          operations: [
            {
              content: '查看',
              icon: 'fa fa-search',
              event: this.handleView,
              attrs: { class: 'p-0 m-2' },
            },
          ],
        },
      ],

      infoVisible: false,
      infoId: '',
      proctStatus: '',
      exportLoading: false,

      countLoading: false,
    }
  },
  computed: {
    ...mapGetters(['clientId', 'user', 'letterType']),
    customerUrl() {
      return window.location.origin + '/credit-h5/#/'
    },
  },
  watch: {},
  created() {
    this.params['service_id.eq'] = this.clientId
    this.$store.dispatch('getLetterType')
    this.getData()
  },
  mounted() {},
  methods: {
    handleView(row = {}) {
      this.infoId = row.customer_related_id
      this.infoVisible = true
    },
    getData(aindex = 1) {
      this.params.index = aindex
      this.loading = true
      this.countLoading = true
      this.$api
        .getData(this.$serviceName, this.tableName, this.params, this.order)
        .then(res => {
          const data = res?.data ?? {}
          this.totalCount = data.totalCount ?? 0
          this.tableData = (data.data ?? []).map(this.dataAdapter)
        })
        .finally(() => {
          this.loading = false
        })
      const { index, size, ...params } = this.params
      this.$api
        .getData(this.$serviceName, this.tableName, {
          ...params,
          groupFunc: `count(distinct(guarantee_project.section_code)),round(sum(tender_bond)|2),round(sum(gua_fee)|2),count(distinct(guarantee_project.enterprise_name))`,
        })
        .then(res => {
          this.countData = res?.data?.[0] ?? {}
        })
        .finally(() => {
          this.countLoading = false
        })
    },
    fetchData(params) {
      return this.$utils.promise(
        this.$api.getData(this.$serviceName, this.tableName, params, this.order)
      )
    },
    async exportExcel(filename) {
      this.exportLoading = true
      exportExcel({
        filename,
        tableColumns: this.tableColumns,
        params: this.params,
        dataAdapter: this.dataAdapter,
        fetchData: this.fetchData,
        onLoaded: () => {
          this.exportLoading = false
        },
      })
    },
    dataAdapter(row, index) {
      row.letterType = this.letterType[row.project_type]
      row.guaRate = row.gua_rate ? row.gua_rate + ' ‰' : ''
      row.index = this.totalCount - index - this.params.size * (this.params.index - 1)
      row.section = row.section_code ? `${row.section_name}-${row.section_code}` : row.section_name
      row.payTime = this.$utils.dateFormat(row.pay_time, 'yyyy-MM-dd')
      row.letterStatus = enumIsExpire[row.is_expire]
      row.invoiceStatus = enumInvoiceStatus[row.invoice_status]

      const date = row.open_time || ''
      row.openTime = `${date.substring(0, 4)}-${date.substring(4, 6)}-${date.substring(
        6,
        8
      )} ${date.substring(8, 10)}:${date.substring(10, 12)}`

      return row
    },
  },
}
</script>

<style lang="scss" scoped></style>
